const jwt = require('jsonwebtoken');
const JWT_SECRET = process.env.JWT_SECRET
const { expiresIn, whiteListHead, whiteList, cookieTokenName } = require('@/config/jwt.config')
// 生成 JWT
const generateToken = (data) => {
  return jwt.sign(data, JWT_SECRET, { expiresIn: expiresIn });
};
// 验证 JWT
const authenticateJWT = (req, res, next) => {
  // 检查当前请求路径是否以白名单中的某个路由开头
  const isWhiteListed = whiteListHead.some(route => req.path.startsWith(route));
  // 如果路径在白名单中，则跳过token验证
  if (isWhiteListed) {
    return next();
  }
  // 白名单全匹配必须是xxx才不需要token校验
  if (whiteList.includes(req.path)) {
    return next();
  }
  // 获取token 尝试通过cookies获取，如果没有则尝试通过header获取
  // 从请求头中获取 Cookie 字符串
  let token
  const cookies = req.headers.cookie;
  if (cookies) {
    // 解析 Cookie 字符串
    const cookiesArray = cookies.split('; ').map(cookie => cookie.split('='));
    const cookiesObject = {};
    for (const [key, value] of cookiesArray) {
      cookiesObject[key] = value;
    }
    token = cookiesObject[cookieTokenName]
  } else {
    // Bearer ***
    token = req.headers.authorization?.split(' ')[1];
  }

  if (token) {
    jwt.verify(token, JWT_SECRET, (err, user) => {
      if (err) {
        // token无效
        return res.status(403).json({ message: 'Invalid token' });
      }
      req.user = user;
      next();
    });
  } else {
    // 没有token
    // res.status(401).json({ message: 'No token provided' });
    const err = new Error('No token provided');
    err.status = 401;
    next(err);
  }
};

module.exports = { generateToken, authenticateJWT };